package controller

import (
	"common/helper"
	myUserHelp "common/userHelp"
	"encoding/json"
	"github.com/valyala/fasthttp"
	"member/model"
	"strings"
)

type MessageController struct{}

// 已读站内信参数
type readMessageParam struct {
	Id string `name:"id" json:"id"`
}

// 删除站内信参数
type deleteMessageParam struct {
	Ids  string `name:"ids" json:"ids"`
	Flag int    `name:"flag" json:"flag"` // 1 精确删除 2 删除所有已读 3删除所有
}

// 内信列表
func (that *MessageController) List(ctx *fasthttp.RequestCtx) {

	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	ty := ctx.QueryArgs().GetUintOrZero("ty")          //1 站内消息 2 活动消息
	isRead := ctx.QueryArgs().GetUintOrZero("is_read") //1 未读 2已读

	if ty > 0 {
		tys := map[int]bool{
			1: true,
			2: true,
		}
		if _, ok := tys[ty]; !ok {
			helper.Print(ctx, false, helper.ParamErr)
			return
		}
	}

	uid := model.GetUidFromToken(ctx)
	if uid == "" {
		helper.Print(ctx, false, helper.AccessTokenExpires)
		return
	}

	Username := myUserHelp.GetMemberName(uid)

	if page == 0 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 1
	}
	data, err := model.MessageList(ty, page, pageSize, isRead, Username)
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, data)
}

// 站内信已读
func (that *MessageController) Num(ctx *fasthttp.RequestCtx) {

	uid := model.GetUidFromToken(ctx)
	if uid == "" {
		helper.Print(ctx, false, helper.AccessTokenExpires)
		return
	}

	Username := myUserHelp.GetMemberName(uid)
	num, err := model.MessageNum(Username)
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, num)
}

// 站内信已读
func (that *MessageController) Read(ctx *fasthttp.RequestCtx) {

	param := readMessageParam{}
	data := ctx.PostBody()
	err := json.Unmarshal(data, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	err = model.MessageRead(param.Id)
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, helper.Success)
}

// 站内信删除
func (that *MessageController) Delete(ctx *fasthttp.RequestCtx) {

	param := deleteMessageParam{}
	data := ctx.PostBody()
	err := json.Unmarshal(data, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	flags := map[int]bool{
		1: true,
		2: true,
		3: true,
	}
	if _, ok := flags[param.Flag]; !ok {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	uid := model.GetUidFromToken(ctx)
	if uid == "" {
		helper.Print(ctx, false, helper.AccessTokenExpires)
		return
	}

	ids := strings.Split(param.Ids, ",")
	if len(ids) > 0 {
		err = model.MessageDeleteByIds(ids)
		if err != nil {
			helper.Print(ctx, false, err.Error())
			return
		}

		helper.Print(ctx, true, helper.Success)
		return
	}

	err = model.MessageDeleteByFilter(myUserHelp.GetMemberName(uid), param.Flag)
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, helper.Success)
}
